﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace RaptorEngine.Components
{
    public class Networkable : Component
    {
        public Dictionary<string, Dictionary<string, object>> RecievedData { get; set; } 
        public Dictionary<string, object> OutgoingData;

        public Networkable(Entity e) : base(e, ComponentType.Networkable)
        {
            RecievedData = new Dictionary<string, Dictionary<string, object>>();
            OutgoingData = new Dictionary<string, object>();
        }

        // Adds a value to the "To send" list that will be used to write a packet.
        public void AddField(int entityID, int componentID, int valueID, object value)
        {
            string key = (entityID.ToString() + "-" + componentID.ToString() + "-" + valueID.ToString());

            OutgoingData.Add(key, value);
        }

        // Returns a value that belongs to the specified component and is of the specified type (valueID).
        public object GetField(int componentID, int valueID)
        {
            if (RecievedData.ContainsKey(componentID.ToString()))
            {
                foreach (KeyValuePair<string, Dictionary<string, object>> keyValuePair in RecievedData)
                {
                    if (keyValuePair.Key == componentID.ToString())
                    {
                        foreach (KeyValuePair<string, object> valuePair in keyValuePair.Value)
                        {
                            if (valuePair.Key == valueID.ToString())
                            {
                                return valuePair.Value;
                            }
                        }
                    }
                }
            }
            return null;
        }

        // Uses the manager to write a packet to be sent.
        public void Send()
        {
            string[] splittedKey;
            foreach (KeyValuePair<string, object> pair in OutgoingData)
            {
                // Write the key.
                GameEngine.Instance.Network.PacketWriter.Write(pair.Key);
                
                // Split key for the typecast
                splittedKey = SplitKey(pair.Key);
                
                // Set the correct typecast.
                if (splittedKey[2] == NetworkConstants.NW_Vector3)
                    GameEngine.Instance.Network.PacketWriter.Write((Vector3)pair.Value);
                if (splittedKey[2] == NetworkConstants.NW_Int)
                    GameEngine.Instance.Network.PacketWriter.Write((int)pair.Value);
                // ...
            }
        }

        public string[] SplitKey(string key)
        {
            char[] delimiterChars = { '-' };
            string[] splittedKey = key.Split(delimiterChars);
            return splittedKey;
        }
    }
}
